package org.github.xhjcehust.dubbo.proxy.util;

import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class FileUtil {

    /**
     * 获取文件列表
     * @param filePath
     * @return
     */
    public static List<File> getFileList(String filePath){
        List<File> files = new ArrayList<>();
        File file = new File(filePath);
        //判断文件或目录是否存在
        if(!file.exists()){
            return null;
        }
        //获取该文件夹下所有的文件
        File[] fileArray= file.listFiles();
        File fileName = null;
        for(int i =0;i<fileArray.length;i++){
            fileName = fileArray[i];
            //判断此文件是否存在
            if(fileName.isDirectory()){

            }else{
                files.add(fileName);
            }
        }

        return files;
    }

    /**
     * 读取文件内容
     * @return
     */
    public static List<String> readFile(String path){
        List<String> lineTxt = new ArrayList<>();
        File file = new File(path);
        StringBuilder result = new StringBuilder();
        try{
            BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));//构造一个BufferedReader类来读取文件
            String s = null;
            while((s = br.readLine())!=null){//使用readLine方法，一次读一行
                lineTxt.add(System.lineSeparator() + s);
            }
            br.close();
        }catch(Exception e){
            e.printStackTrace();
        }
        return lineTxt;
    }

    public static void main(String[] args) {
        List<File> list = FileUtil.getFileList("C:\\Users\\大糊\\Desktop\\1");
        List<String> lines = new ArrayList<>();
        for (File f : list){
            lines.addAll(FileUtil.readFile(f.getPath()));
        }
        Map<String,List<String>> map = new HashMap<>();
        for (String s : lines){
            String jsonStr = s.substring(s.indexOf("json:")+5,s.indexOf(",msg:"));
            JSONObject json = JSONObject.parseObject(jsonStr);
            String msg = s.substring(s.indexOf(",msg:")+5);
            if (!map.containsKey(msg)){
                List<String> jsonList = new ArrayList<>();
                map.put(msg,jsonList);
            }
            map.get(msg).add(json.getJSONObject("memberCompanyInfoDTO").getString("companyName"));
        }
        System.out.println(JSONObject.toJSONString(map));
    }
}
